<template>
  <div class="article-list" ref="article-list">
    <van-pull-refresh
      v-model="isPullRefresh"
      :success-text="refreshText"
      @refresh="onRefresh"
      :success-duration="1000"
    >
       <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <article-item
          v-for="(item,index) in articlesList"
           :key="index"
           :article="item"
           />
        </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticle } from '@/api/article.js'
import articleItem from '@/components/article-item/index.vue'
import {debounce} from 'lodash'
export default {
  props:{
    channel:{
      type:Object,
      required:true
    }
  },
  name: 'ArticleList',
  components: {
    articleItem
   },
  directives: { },
  data() {
    return {
        refreshText:'',//下拉刷新成功文字提示
        isPullRefresh:false,//下拉刷新
        pretime:Date.now(),//下一页的数据时间戳 类似分页
        articlesList: [],//数据列表
        loading: false, //控制加载中的数据，loading状态
        finished: false,//控制加载结束的状态，当加载结束，不再触发加载更多
        scrollTop:0,//列表滚动距离
    };
  },
  mounted() {
    this.$refs['article-list'].onscroll=debounce(()=>{
      this.scrollTop=this.$refs['article-list'].scrollTop
    },50)
  },
  activated(){
    //从缓存中被激活
    //把记录的距离重新设置回去
    this.$refs['article-list'].scrollTop=this.scrollTop
  },
  deactivated(){
    //组件失活
  },
  methods: {
    async onLoad() {
      // 异步更新数据
     const { data }=await getArticle({
        channel_id:this.channel.id,
        timestamp:this.pretime,//类似页码
        with_top:1,
     })
     //console.log(data.data)
     this.articlesList.push(...data.data.results)
     this.loading=false;
     //数据是否全部加载完成
     if(data.data.results.length){
       //更新下一页数据
       this.pretime=data.data.pre_timestamp
     }else{
       //没有数据了
       this.finished=true
     }
    },
    async onRefresh(){
      //1.请求获取数据
       const { data }=await getArticle({
            channel_id:this.channel.id,
            timestamp:Date.now(),//类似页码
            with_top:1,
        })
         this.articlesList.unshift(...data.data.results)
         //2.把数据放到数据列表中
         //3.关闭刷新的状态
         this.isPullRefresh=false
         this.refreshText=`更新了${data.data.results.length}条数据`
    }
  },
};
</script>

<style lang="less" scoped>
.article-list{
  position: fixed;
  left:0;
  right:0;
  top:90px;
  bottom: 50px;
  overflow-y:auto;
}
</style>
